<template>
  <el-dialog
    v-model="dialogVisible"
    title="商品评价"
    width="500px"
    @close="handleClose"
  >
    <div class="evaluation-form">
      <div v-for="item in goodsList" :key="item.gid" class="goods-item">
        <div class="goods-info">
          <img :src="item.goodsImg?.[0] || '/default-goods.png'" alt="商品图片" class="goods-image" />
          <div class="goods-details">
            <h4>{{ item.goodsName }}</h4>
            <p class="price">¥{{ item.price }}</p>
          </div>
        </div>
        
        <div class="evaluation-content">
          <div class="rating-section">
            <label>评分：</label>
            <StarRating v-model="item.rating" />
          </div>
          
          <div class="comment-section">
            <label>评价内容：</label>
            <el-input
              v-model="item.comment"
              type="textarea"
              :rows="4"
              placeholder="请分享您对商品的使用感受..."
              maxlength="500"
              show-word-limit
            />
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          提交评价
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import StarRating from './StarRating.vue'
import { evaluateGoodsAPI } from '@/apis/goods'
import { useUserStore } from '@/stores/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  goods: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(props.visible)
const goodsList = ref([])
const submitting = ref(false)

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    initGoodsList()
  }
})

watch(() => props.goods, (newVal) => {
  if (newVal && newVal.length > 0) {
    initGoodsList()
  }
})

const initGoodsList = () => {
  goodsList.value = props.goods.map(item => ({
    ...item,
    rating: 5,
    comment: ''
  }))
}

const handleClose = () => {
  emit('update:visible', false)
  goodsList.value = []
}

const handleSubmit = async () => {
  // 验证所有商品都有评价内容
  const invalidItems = goodsList.value.filter(item => !item.comment.trim())
  if (invalidItems.length > 0) {
    ElMessage.warning('请填写所有商品的评价内容')
    return
  }

  submitting.value = true
  
  try {
    const userStore = useUserStore()
    
    // 调试信息：检查用户信息是否正确
    console.log('用户信息:', userStore.userInfo)
    console.log('用户UID:', userStore.userInfo.uid)
    
    if (!userStore.userInfo.uid) {
      ElMessage.error('用户信息获取失败，请重新登录')
      return
    }
    
    const promises = goodsList.value.map(item => {
      console.log('发送评价数据:', {
        gid: item.gid,
        uid: userStore.userInfo.uid,
        evaluation: item.comment,
        stars: item.rating
      })
      
      return evaluateGoodsAPI({
        gid: item.gid,
        uid: userStore.userInfo.uid,
        evaluation: item.comment,
        stars: item.rating
      })
    })
    
    await Promise.all(promises)
    
    ElMessage.success('评价提交成功！')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('评价提交失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('评价提交失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.evaluation-form {
  max-height: 60vh;
  overflow-y: auto;
}

.goods-item {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.goods-item:last-child {
  margin-bottom: 0;
}

.goods-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.goods-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
}

.goods-details h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.price {
  margin: 0;
  color: #ff5000;
  font-weight: bold;
}

.evaluation-content {
  space-y: 16px;
}

.rating-section,
.comment-section {
  margin-bottom: 16px;
}

.rating-section label,
.comment-section label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>